//
//  XLChannelView.m
//  XLChannelControlDemo
//
//  Created by MengXianLiang on 2017/3/3.
//  Copyright © 2017年 MengXianLiang. All rights reserved.
//

#import "XLChannelView.h"
#import "XLChannelItem.h"
#import "XLChannelHeader.h"

//菜单列数
static NSInteger ColumnNumber = 3;


@interface XLChannelView ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UICollectionView *_collectionView;
    //被拖拽的item
    XLChannelItem *_dragingItem;
    //正在拖拽的indexpath
    NSIndexPath *_dragingIndexPath;
    //目标位置
    NSIndexPath *_targetIndexPath;
}

@property (nonatomic , strong) UIButton * adjustButton;


@end

@implementation XLChannelView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self buildUI];
    }
    return self;
}

-(void)buildUI{
    
    CGFloat CellMarginX = [UIScreen zj_screenWScale] * 15;
    CGFloat CellMarginY = [UIScreen zj_screenHScale] * 10;
    self.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat cellWidth = ([UIScreen zj_screenWith] - (ColumnNumber + 1) * CellMarginX)/ColumnNumber;
    flowLayout.itemSize = CGSizeMake(cellWidth,ItemHeight * 60);
    flowLayout.sectionInset = UIEdgeInsetsMake(CellMarginY, CellMarginX, CellMarginY, CellMarginX);
    flowLayout.minimumLineSpacing = CellMarginY;
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.headerReferenceSize = CGSizeMake([UIScreen zj_screenWith], ItemHeight * 60);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 100) collectionViewLayout:flowLayout];
    _collectionView.showsHorizontalScrollIndicator = false;
    _collectionView.showsVerticalScrollIndicator = false;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[XLChannelItem class] forCellWithReuseIdentifier:@"XLChannelItem"];
    [_collectionView registerClass:[XLChannelHeader class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XLChannelHeader"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.scrollEnabled = NO;
    [self addSubview:_collectionView];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    longPress.minimumPressDuration = 0.3f;
    [_collectionView addGestureRecognizer:longPress];
    
    _dragingItem = [[XLChannelItem alloc] initWithFrame:CGRectMake(0, 0, cellWidth, ItemHeight * 60)];
    _dragingItem.hidden = true;
    [_collectionView addSubview:_dragingItem];
    
    [self addSubview:self.adjustButton];
    
    self.adjustButton.sd_layout.topSpaceToView(_collectionView , ItemHeight * 10).leftSpaceToView(self , ItemWidth * 30).widthIs([UIScreen zj_screenWith] - ItemWidth * 60).heightIs(ItemHeight * 60);
}

#pragma mark -
#pragma mark LongPressMethod
-(void)longPressMethod:(UILongPressGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:_collectionView];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChanged:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd];
            break;
        default:
            break;
    }
}

//拖拽开始 找到被拖拽的item
-(void)dragBegin:(CGPoint)point{
    _dragingIndexPath = [self getDragingIndexPathWithPoint:point];
    if (!_dragingIndexPath) {return;}
    [_collectionView bringSubviewToFront:_dragingItem];
    XLChannelItem *item = (XLChannelItem*)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
    if (item.isFixed) {
        _dragingIndexPath = nil;
        return;
    }
    item.isMoving = YES;
    //更新被拖拽的item
    _dragingItem.hidden = NO;
    _dragingItem.frame = item.frame;
    _dragingItem.model = item.model;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
}

//正在被拖拽、、、
-(void)dragChanged:(CGPoint)point{
    if (!_dragingIndexPath) {return;}
    _dragingItem.center = point;
    _targetIndexPath = [self getTargetIndexPathWithPoint:point];
    //交换位置 如果没有找到_targetIndexPath则不交换位置
    if (_dragingIndexPath && _targetIndexPath) {
        //更新数据源
        [self rearrangeInUseTitles];
        //更新item位置
        [_collectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];
        _dragingIndexPath = _targetIndexPath;
    }
}

//拖拽结束
-(void)dragEnd{
    if (!_dragingIndexPath) {return;}
    CGRect endFrame = [_collectionView cellForItemAtIndexPath:_dragingIndexPath].frame;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
    [UIView animateWithDuration:0.3 animations:^{
        _dragingItem.frame = endFrame;
    }completion:^(BOOL finished) {
        _dragingItem.hidden = YES;
        XLChannelItem *item = (XLChannelItem*)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
        item.isMoving = NO;
//        [_collectionView reloadData];
    }];
}

#pragma mark -
#pragma mark 辅助方法

//获取被拖动IndexPath的方法
-(NSIndexPath*)getDragingIndexPathWithPoint:(CGPoint)point{
    NSIndexPath* dragIndexPath = nil;
    //最后剩一个怎不可以排序
    if (self.inUseTitles.count == 1) {return dragIndexPath;}
    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        //找出相对应的Item
        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            dragIndexPath = indexPath;
            break;
        }
    }
    return dragIndexPath;
}

//获取目标IndexPath的方法
-(NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)point{
    NSIndexPath *targetIndexPath = nil;
    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        //如果是自己不需要排序
        if ([indexPath isEqual:_dragingIndexPath]) {continue;}
        //在第一组中找出将被替换位置的Item
        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            targetIndexPath = indexPath;
        }
    }
    return targetIndexPath;
}


#pragma mark -
#pragma mark CollectionViewDelegate&DataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.inUseTitles.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    XLChannelHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XLChannelHeader" forIndexPath:indexPath];
    YBMeetingReturnHeadModel * model = [[YBMeetingReturnHeadModel alloc]init];
    if (self.adjustButton.selected) {
        model.CODE_NAME = @"已选内容:  (长按拖动可以排序,可删除)";
    }
    else{
        model.CODE_NAME = @"已选内容:";
    }
    headerView.model = model;
    
    return headerView;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellId = @"XLChannelItem";
    XLChannelItem* item = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    item.deleteButton.hidden = !self.adjustButton.selected;
    item.model = self.inUseTitles[indexPath.row];
    item.isFixed = !self.adjustButton.selected;
    item.deleteButton.tag = 1000 + indexPath.row;
    [item.deleteButton addTarget:self action:@selector(option_deleteButton:) forControlEvents:UIControlEventTouchUpInside];
    return  item;
}

-(void)option_deleteButton:(UIButton *)sender{
    NSInteger index = sender.tag - 1000;
    NSIndexPath * tempIndexPath = [NSIndexPath indexPathForItem:index inSection:0];
    XLChannelItem * item = (XLChannelItem *)[_collectionView cellForItemAtIndexPath:tempIndexPath];
    if (!item.isFixed) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didClickDeleteButtonWithIndex:)]) {
            [self.delegate didClickDeleteButtonWithIndex:tempIndexPath.row];
        }
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.adjustButton.selected) {
        XLChannelItem * item = (XLChannelItem *)[_collectionView cellForItemAtIndexPath:indexPath];
        if (!item.isFixed) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(didClickDeleteButtonWithIndex:)]) {
                [self.delegate didClickDeleteButtonWithIndex:indexPath.row];
            }
        }
    }
}

#pragma mark -
#pragma mark 刷新方法
//拖拽排序后需要重新排序数据源
-(void)rearrangeInUseTitles
{
//    XLChannelItem * item1 = (XLChannelItem *)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
//    XLChannelItem * item2 = (XLChannelItem *)[_collectionView cellForItemAtIndexPath:_targetIndexPath];
//    CGFloat tempTag = item1.deleteButton.tag;
//    item1.deleteButton.tag = item2.deleteButton.tag;
//    item2.deleteButton.tag = tempTag;
    id obj = [_inUseTitles objectAtIndex:_dragingIndexPath.row];
    [_inUseTitles removeObjectAtIndex:_dragingIndexPath.row];
    [_inUseTitles insertObject:obj atIndex:_targetIndexPath.row];
}

-(void)reloadData
{
    [_collectionView reloadData];
}


-(void)changeDataSourceWithArray:(NSMutableArray *)array{
    self.inUseTitles = array;
    [_collectionView reloadData];
    NSInteger lineCount = 0;
    if (array.count > 0) {
        lineCount = (array.count - 1) / 3 + 1;
    }
    CGFloat intervalHeight = 0.f;
    if (lineCount == 0) {
        intervalHeight = 0.f;
    }
    else{
        intervalHeight = (lineCount - 1) * ItemHeight * 20;
    }
    _collectionView.frame = CGRectMake(0, 0, [UIScreen zj_screenWith], ItemHeight * 100 + lineCount * ItemHeight * 60 + intervalHeight);
}


-(void)option_adjustButton:(UIButton *)sender{
    sender.selected = !sender.selected;
    [_collectionView reloadData];
}


-(UIButton *)adjustButton
{
    if (!_adjustButton) {
        _adjustButton = [ToolClass createButtonWithFrame:CGRectMake(ItemWidth * 30, 0, [UIScreen zj_screenWith] - ItemWidth * 60, ItemHeight * 60) text:@"调整已选内容顺序" textColor:[UIColor textGrayColor] imageName:@"" font:16];
        [_adjustButton setTitle:@"完成" forState:UIControlStateSelected];
        _adjustButton.backgroundColor = [UIColor zj_colorWithHexString:@"ffb0b0"];
        [_adjustButton addTarget:self action:@selector(option_adjustButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _adjustButton;
}

@end
